package cn.chengpengper.shortlink.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @author huchengpeng
 * @version 1.0.0
 * @date 2023/6/18 22:14
 * @description 通用工具类
 */
@Slf4j
public class CommonUtil {

    private static final String UNKNOWN = "unknown";

    private static final String LOCALHOST = "127.0.0.1";

    private static final String COMMA = ",";

    private static final Integer FIFTEEM = 15;

    private static final Random RANDOM = new Random();

    private static final String ALL_CHAR_NUM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWSYZabcdefghijklmnopqrstuvwsyz";

    /**
     * 获取请求 IP
     *
     * @param request 请求体
     * @return String IP 地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (StringUtils.isBlank(ipAddress) || UNKNOWN.equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-Ip");
            }
            if (StringUtils.isBlank(ipAddress) || UNKNOWN.equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-Ip");
            }
            if (StringUtils.isBlank(ipAddress) || UNKNOWN.equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals(LOCALHOST)) {
                    // 根据网卡取本机配置IP
                    InetAddress inet = InetAddress.getLocalHost();
                    ipAddress = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况，第一个 IP 为客户端真实 IP，多个 IP 按照 "," 分割
            if (Objects.nonNull(ipAddress) && ipAddress.length() > FIFTEEM) {
                if (ipAddress.indexOf(COMMA) > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(COMMA));
                }
            }
        } catch (Exception e) {
            ipAddress = "";
        }
        return ipAddress;
    }

    /**
     * 获取全部请求头
     *
     * @param request 请求体
     * @return Map<String, String> 所有请求头数据
     */
    public static Map<String, String> getAllRequestHeader(HttpServletRequest request) {
        Enumeration<String> headerNames = request.getHeaderNames();
        Map<String, String> map = new HashMap<>();
        while (headerNames.hasMoreElements()) {
            String key = headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }

    /**
     * MD5 加密
     *
     * @param data 待加密字符串
     * @return String MD5加密后的字符串
     */
    public static String MD5(String data) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] array = md5.digest(data.getBytes(StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            for (byte item : array) {
                sb.append(Integer.toHexString((item & 0xFF) | 0x100), 1, 3);
            }
            return sb.toString().toUpperCase(Locale.ROOT);
        } catch (NoSuchAlgorithmException ignored) {
        }
        return null;
    }

    /**
     * 获取验证码随机数
     *
     * @param length 验证码长度
     * @return String 验证码
     */
    public static String getRandomCode(int length) {
        String sources = "0123456789";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(sources.charAt(RANDOM.nextInt(sources.length())));
        }
        return sb.toString();
    }

    /**
     * 获取当前时间戳
     *
     * @return long 当前时间戳
     */
    public static long getCurrentTimestamp() {
        return System.currentTimeMillis();
    }

    public static Date now() {
        return new Date();
    }

    /**
     * 生成 UUID
     *
     * @return String UUID 字符串
     */
    public static String generateUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }

    /**
     * 生成随机数字和字母组成的字符串
     *
     * @param length 字符串长度
     * @return String 随机字符串
     */
    public static String getStringNumRandom(int length) {
        StringBuilder salt = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            salt.append(ALL_CHAR_NUM.charAt(RANDOM.nextInt(ALL_CHAR_NUM.length())));
        }
        return salt.toString();
    }

    public static void sendJsonMessage(HttpServletResponse response, Object obj) {
        response.setContentType("application/json; charset=utf-8");

        try (PrintWriter writer = response.getWriter()) {
            writer.print(JsonUtil.obj2Bytes(obj));
            response.flushBuffer();
        } catch (IOException e) {
            log.error("响应 json 数据给前端异常:", e);
        }
    }

}
